package com.dingreading.cloud.admin.util.bean;

import com.dingreading.cloud.admin.entity.GoodsWetPrice;
import com.dingreading.cloud.admin.service.GoodsWetPriceService;
import com.dingreading.cloud.common.util.DoubleUtil;
import com.dingreading.cloud.common.util.NepUtil;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;

@Component
public class GoodsWetAvgUtil {

    public static GoodsWetAvgUtil util;

    @Resource
    private GoodsWetPriceService goodsWetPriceService;

    @PostConstruct
    public void init() {
        util = this;
    }

    /**
     * 商品入库，计算入库商品的加权平均价
     */
    public static void updateGoodsWetAvgPrice(String name, Long goodsId, Long goodsTypeId, Integer realNum, Double inAmount) {
        GoodsWetPrice goodsWetPrice = util.goodsWetPriceService.getByGoodsIdAndGoodsTypeId(goodsId, goodsTypeId);
        if (null != goodsWetPrice) {
            int usableNum = NepUtil.nullToZero(goodsWetPrice.getUsableNum());
            usableNum += realNum;
            double usablePrice = NepUtil.nullToZero(goodsWetPrice.getUsablePrice());
            usablePrice = DoubleUtil.sum(usablePrice, inAmount);
            double div = 0d;
            if (usableNum != 0 && usablePrice != 0) {
                div = DoubleUtil.div(usablePrice, usableNum, 4);
            }
            boolean l = util.goodsWetPriceService.updateWetAvgPrice(goodsWetPrice.getId(), goodsTypeId, usableNum, usablePrice, div);
            if (!l) System.out.println("商品的加权平均价更新失败！商品名：" + name);
        } else {
            GoodsWetPrice newData = PurchaseUtil.newGoodsWetPrice(goodsId, goodsTypeId, realNum, inAmount);
            util.goodsWetPriceService.saveOrUpdate(newData);
        }
    }

    /**
     * 退回入库单的库存数，扣除入库商品的加权平均价
     */
    public static void deductGoodsWetAvgPrice(GoodsWetPrice goodsWetPrice, String name, Integer realNum, Double inAmount, Date time) {
        if (null == goodsWetPrice) System.out.println("入库商品相关加权记录不存在");
        int usableNum = NepUtil.nullToZero(goodsWetPrice.getUsableNum());
        usableNum -= realNum;
        double usablePrice = NepUtil.nullToZero(goodsWetPrice.getUsablePrice());
        usablePrice = DoubleUtil.sub(usablePrice, inAmount);
        double div = 0d;
        if (usableNum != 0 && usablePrice != 0) {
            div = DoubleUtil.div(usablePrice, usableNum, 4);
        }
        boolean l = util.goodsWetPriceService.updateWetAvgPrice(goodsWetPrice.getId(), goodsWetPrice.getGoodsTypeId(),
                usableNum, usablePrice, div);
        if (!l) System.out.println("商品的加权平均价更新失败！商品名：" + name);
    }
}
